package com.deparse.dpframe.ui.widget;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;

import com.deparse.dpframe.ui.widget.DPViewPager;

/**
 * Created by hsy on 2016/4/11.
 */
public class DPAutoScrollViewPager extends DPViewPager {
    private int currentItem;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (null != mOnAutoScrollListener) {
                mOnAutoScrollListener.onAutoScrollStart(currentItem);
            }
            currentItem++;
            if (getAdapter().getCount() == currentItem) {
                currentItem = 0;
                setCurrentItem(currentItem,false);
                sendEmptyMessageDelayed(0, mDuration);
            }else {

                setCurrentItem(currentItem);
                sendEmptyMessageDelayed(0, mDuration);
            }


        }
    };
    private OnPageChangeListener mOnPageChangeListener = new OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            if (null != mOnAutoScrollListener) {
                mOnAutoScrollListener.onAutoScrollFinish(getCurrentItem());
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    private OnAutoScrollListener mOnAutoScrollListener;
    private long mDuration = 5000;

    public DPAutoScrollViewPager(Context context) {
        super(context);
        init(context);
    }

    public DPAutoScrollViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
        addOnPageChangeListener(mOnPageChangeListener);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        int act = MotionEvent.ACTION_MASK & ev.getAction();
        if (MotionEvent.ACTION_DOWN == act) {
            handler.removeMessages(0);
        }
        if (MotionEvent.ACTION_UP == act || MotionEvent.ACTION_CANCEL == act) {
            startScroll(mDuration, mOnAutoScrollListener);
        }
        return super.dispatchTouchEvent(ev);
    }

    public void startScroll(long duration, OnAutoScrollListener listener) {
        this.mOnAutoScrollListener = listener;
        this.mDuration = duration;

        currentItem = getCurrentItem();
        handler.removeMessages(0);
        handler.sendEmptyMessageDelayed(0, mDuration);
    }

    public void stopScroll() {
        handler.removeMessages(0);
    }

    public interface OnAutoScrollListener {
        void onAutoScrollStart(int positionBefore);

        void onAutoScrollFinish(int positionAfter);
    }
}
